package navigation;

import config.*;

/**
 * Navigator that goes to the red point and seeks unknown fields
 *
 * Prioritys: unknown right, unknown forward, unknown left, unknown backward.
 * If no unknown field is in direct proximity the shortest known path to the next unknown field is picked.
 * Prefers paths to the south.
 *
 * @author hyurah
 */

public class GoToUnknownFieldNavigator extends Navigator{

	private PathQueue way = null;

	/**
	 * Constructs an GoToUnknownFieldNavigator with empty map data
	 */

	public GoToUnknownFieldNavigator() {
		super();
	}

	/**
	 * Constructs an GoToUnknownFieldNavigator with data specified by the old navigator
	 *
	 * @param oldNavigator old navigator for data retrievel
	 * @throws IllegalMapStateException when every reachable field is known
	 */

	public GoToUnknownFieldNavigator(Navigator oldNavigator) {
		super(oldNavigator);
	}

	/**
	 * Decide direction to drive to next
	 *
	 * @return direction to drive to
	 */

	public int decideDirection() throws IllegalMapStateException {
		int rotation = Config.GORIGHT? Direction.LEFT : Direction.RIGHT;
		int direction = Config.GORIGHT? Direction.RIGHT : Direction.LEFT;
		int xTarget;
		int yTarget;
		boolean found=false;
		for(int i=0; i<4 && !found; i++) {
			if(isPassable((direction+facingDirection)%4)) {
				xTarget = xPosition;
				yTarget = yPosition;
				switch((direction+facingDirection)%4) {
					case Direction.NORTH: yTarget--; break;
					case Direction.EAST: xTarget++; break;
					case Direction.SOUTH: yTarget++; break;
					case Direction.WEST: xTarget--; break;
				}
				if(!map.fieldIsKnown(xTarget, yTarget)) {
					found=true;
					way = null;
				}
			}
			if(!found) {
				direction=(direction+rotation)%4;
			}
		}
		if(!found) {
			if(way==null || way.size()<2) {
				way = Wayfinder.findShortestPath(SearchTarget.UNKNOWNFIELD, map, xPosition, yPosition);
			}
			if(way.getPoint(0).getX()!=xPosition || way.getPoint(0).getY()!=yPosition) {
				way = Wayfinder.findShortestPath(SearchTarget.UNKNOWNFIELD, map, xPosition, yPosition);
			}
			direction = (way.popPoint().getDirection()+4-facingDirection)%4;
		}
		return direction;
	}

}
